package com.yogee.topseller.fragment.productdetail;

import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.yogee.core.base.HttpFragment;
import com.yogee.core.utils.ToastUtils;
import com.yogee.topseller.R;
import com.yogee.topseller.activity.ProductDetailsActivity_old;
import com.yogee.topseller.adapter.ImagesAdapter;
import com.yogee.topseller.bean.ProductInfoBean;
import com.yogee.topseller.view.MyScrollView;
import com.yogee.topseller.view.PublicStaticClass;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * Created by zwj on 2017/12/7.
 */

public class ProductPictFragment extends BaseFragment {
    @BindView(R.id.id_stickynavlayout_innerscrollview)
    RecyclerView pic_list_rv;
    @BindView(R.id.details_material_ll)
    LinearLayout details_material_ll;
    @BindView(R.id.id_empty_view)
    View id_empty_view;
    @BindView(R.id.iv_empty)
    ImageView iv_empty;
    private int smallImgWidth;
    private ImagesAdapter adapter;

    private ProductInfoBean beans;
    private File file1;
    // 下载失败
    public static final int DOWNLOAD_ERROR = 2;
    // 下载成功
    public static final int DOWNLOAD_SUCCESS = 1;
    private ProgressDialog mProgressDialog;

    @BindView(R.id.oneScrollview)
    MyScrollView oneScrollView;

    Unbinder unbinder1;
//    private static String[] images = {"http://7xi8d6.com1.z0.glb.clouddn.com/2017-05-08-18252341_289400908178710_9137908350942445568_n.jpg",
//            "http://7xi8d6.com1.z0.glb.clouddn.com/2017-05-05-18251898_1013302395468665_8734429858911748096_n.jpg",
//            "http://7xi8d6.com1.z0.glb.clouddn.com/2017-05-04-18299181_1306649979420798_1108869403736276992_n.jpg",
//            "http://7xi8d6.com1.z0.glb.clouddn.com/2017-05-02-926821_1453024764952889_775781470_n.jpg",
//            "http://7xi8d6.com1.z0.glb.clouddn.com/2017-04-28-18094719_120129648541065_8356500748640452608_n.jpg",
//            "http://7xi8d6.com1.z0.glb.clouddn.com/2017-04-27-17934080_117414798808566_8957027985114791936_n.jpg",
//            "http://7xi8d6.com1.z0.glb.clouddn.com/2017-04-25-13651793_897557617014845_571817176_n.jpg",
//            "http://7xi8d6.com1.z0.glb.clouddn.com/2017-04-24-18013547_1532023163498554_215541963087151104_n.jpg"};

    private String[] images;
    @Override
    protected int getLayoutId() {
        return R.layout.fragment_product_pic;
    }

    @Override
    protected void initView() {

        oneScrollView.setScrollListener(new MyScrollView.ScrollListener() {
            @Override
            public void onScrollToBottom() {

            }

            @Override
            public void onScrollToTop() {

            }

            @Override
            public void onScroll(int scrollY) {
                if (scrollY == 0) {
                    PublicStaticClass.IsTop = true;
                } else {
                    PublicStaticClass.IsTop = false;
                }
            }

                @Override
                public void notBottom() {

            }

        });
        iv_empty.setImageResource(R.drawable.nodata1);
        beans = (ProductInfoBean) getArguments().getSerializable("baseInfo");
        images = beans.getInfo().get(0).getImg().split(",");
        smallImgWidth = getResources().getDisplayMetrics().widthPixels / 4;
        pic_list_rv.setLayoutManager(new GridLayoutManager(getActivity(),4));
        adapter = new ImagesAdapter(getActivity(),smallImgWidth);
        pic_list_rv.setAdapter(adapter);
        adapter.addData(images);

        //材料
        final List<ProductInfoBean.MaterialBean> materialBeen = beans.getMaterial();
        details_material_ll.removeAllViews();
        if (materialBeen.size() > 0 && materialBeen != null) {
            id_empty_view.setVisibility(View.GONE);
            for (int i = 0; i < materialBeen.size(); i++) {
                View v = LayoutInflater.from(getActivity()).inflate(R.layout.product_details_material_layout, null);
                ImageView iv = (ImageView) v.findViewById(R.id.material_iv);
                TextView tv = (TextView) v.findViewById(R.id.material_tv);
                if (materialBeen.get(i).getType().equals("doc")||materialBeen.get(i).getType().equals("docx")) {
                    iv.setImageResource(R.mipmap.product_w_blue);
                } else if (materialBeen.get(i).getType().equals("pdf")) {
                    iv.setImageResource(R.mipmap.product_p_red);
                } else {
                    iv.setImageResource(R.mipmap.product_e_green);
                }
                tv.setText(materialBeen.get(i).getName());
                RelativeLayout rl = (RelativeLayout) v.findViewById(R.id.material_rl);
                final int finalI = i;

                rl.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        download(materialBeen.get(finalI).getUrl(), materialBeen.get(finalI).getName());
                    }
                });
                details_material_ll.addView(v);
            }
        }else{
            id_empty_view.setVisibility(View.VISIBLE);
        }

        mProgressDialog = new ProgressDialog(getActivity() );
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        mProgressDialog.setCancelable(false);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder1 = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder1.unbind();
    }

    public static String getFileName(String serverurl) {
        return serverurl.substring(serverurl.lastIndexOf("/") + 1);
    }

    private void download(final String url, String name) {
        mProgressDialog.show();
        //截取最后3位 作为文件名
        String s = name;
        Log.d("asbdasd", s);
        //文件存储
        file1 = new File(Environment.getExternalStorageDirectory(),getFileName(s));
        new Thread() {
            public void run() {

                File haha = new File(file1.getAbsolutePath());
                //判断是否有此文件
                if (haha.exists()) {
                    //有缓存文件,拿到路径 直接打开
                    Message msg = Message.obtain();
                    msg.obj = haha;
                    msg.what = DOWNLOAD_SUCCESS;
                    handler.sendMessage(msg);
                    mProgressDialog.dismiss();
                    return;
                }
                //本地没有此文件 则从网上下载打开
                File downloadfile = downLoad(url, file1.getAbsolutePath(), mProgressDialog);
                Message msg = Message.obtain();
                if (downloadfile != null) {
                    // 下载成功,安装....
                    msg.obj = downloadfile;
                    msg.what = DOWNLOAD_SUCCESS;
                } else {
                    // 提示用户下载失败.
                    msg.what = DOWNLOAD_ERROR;
                }
                handler.sendMessage(msg);
                mProgressDialog.dismiss();
            }
        }.start();
    }

    /**
     * 下载完成后  直接打开文件
     */
    Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case DOWNLOAD_SUCCESS:
                    File file = (File) msg.obj;
                    Intent intent = new Intent("android.intent.action.VIEW");
                    intent.addCategory("android.intent.category.DEFAULT");
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    intent.setDataAndType(Uri.fromFile(file), "application/pdf");
                    startActivity(Intent.createChooser(intent, "请选择要打开的工具"));
                    break;
                case DOWNLOAD_ERROR:
                    ToastUtils.showToast(getActivity(), "文件加载失败");
                    break;
            }
        }
    };

    /**
     * 传入文件 url  文件路径  和 弹出的dialog  进行 下载文档
     */
    public static File downLoad(String serverpath, String savedfilepath, ProgressDialog pd) {
        try {
            URL url = new URL(serverpath);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5000);
            if (conn.getResponseCode() == 200) {
                int max = conn.getContentLength();
                pd.setMax(max);
                InputStream is = conn.getInputStream();
                File file = new File(savedfilepath);
                FileOutputStream fos = new FileOutputStream(file);
                int len = 0;
                byte[] buffer = new byte[1024];
                int total = 0;
                while ((len = is.read(buffer)) != -1) {
                    fos.write(buffer, 0, len);
                    total += len;
                    pd.setProgress(total);
                }
                fos.flush();
                fos.close();
                is.close();
                return file;
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public String getTitle() {
        return "相关图片";
    }
}
